package com.ketayao.commandparser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import com.ketayao.excel.helper.ExcelExportHelper;

/** 
 * @author 	<a href="mailto:ketayao@gmail.com">ketayao</a>
 * @since   2014年2月12日 上午9:57:49 
 */
public class ParseSuccess {

	protected final static String END_INDEX = "---    END";
	
	protected final static String FORMAT = "命令-----{0}:;";
	protected final static MessageFormat messageFormat = new MessageFormat(FORMAT);
	
	protected Map<String, Integer> headMap = new HashMap<String, Integer>();
	protected Row firstRow;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
//		String[] commands = new String[]{
//				//"LST DRX",
//				//"LST ENODEBALGOSWITCH",
//				//"LST RRCCONNSTATETIMER",
//				//"LST CELLRESEL",
//				//"LST CELL"
//				//"LST CELLPUCCHALGO",
//				"LST CELLSTANDARDQCI",
//				//"LST GERANNFREQGROUP",
//				"LST INTERRATPOLICYCFGGROUP"
//				//"LST CNOPERATORHOCFG",
//				//"LST CSFALLBACKBLINDHOCFG",
//				//"LST INTERRATHOUTRANGROUP",
//				//"LST DRXPARAGROUP",
//				//"LST INTERRATHOCOMMGROUP"
//		};
		
		ParseSuccess parser = new ParseSuccess();
		//String path = "E:\\git-repository-dev\\command-parser\\src\\test\\resources\\MMLTaskResult_CreateAt_2014-02-08091134.txt";
		//String path = "E:\\git-repository-dev\\command-parser\\src\\test\\resources\\多文档.txt";
		String path = args[0];
		String c = args[1];
		//String c = "LST GERANNFREQGROUPARFCN";
		try {
//			for (String c : commands) {
//				System.out.println(c);
//				parser.handle(path, c);
//			}
			parser.handle(path, c);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void handle(String path, String command) {
		File file = new File(path);
		
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		String commandIndex = messageFormat.format(new Object[]{command});
		
		List<List<String>> units = new ArrayList<List<String>>();
		List<String> lines = new ArrayList<String>();
		String line = null;
		boolean isCommandStart = false;
		boolean isMutilCotent = false;
		boolean isSuccess = false;
		try {
			while ((line = reader.readLine()) != null) {
				if (line.equals("==========成功命令==========")) {
					isSuccess = true;
					continue;
				}
				
				if (line.matches("=+")) {
					isSuccess = false;
					continue;
				}
				
				if (isSuccess == false) {
					continue;
				}
				
				if (isCommandStart && line.matches("仍有后续报告输出")) {
					isMutilCotent = true;
					// 删除前3行
					lines = lines.subList(0, lines.size() - 3);
					continue;
				}
				
				if (isMutilCotent == false) {
					if (line.matches(commandIndex) && isCommandStart == false) {
						lines.add(line);
						isCommandStart = true;
						continue;
					} 
					
					if (isCommandStart) {
						lines.add(line);
					}
					
					if (line.matches(END_INDEX) && isCommandStart) {
						units.add(lines);
						lines = new ArrayList<String>();
						isCommandStart = false;
						isMutilCotent = false;
					}
				} else {
					if (line.matches("----+")) {
						//前进读2行
						reader.readLine();
						reader.readLine();
						
						isMutilCotent = false;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		handleExcel(units, command);
	}
	
	public void handleExcel(List<List<String>> units, String command) {
		if (units.isEmpty()) {
			System.err.println("没有找到" + command + "的数据！！！！！！");
			return;
		}
		
		ExcelExportHelper excelExportHelper = new ExcelExportHelper(); 
		handleHead(units.get(0), excelExportHelper);
		
		while (!units.isEmpty()) {
			List<String> lines = units.remove(0);
			handleContent(lines, excelExportHelper);
		}
		
		excelExportHelper.export("d:/" + command + ".xls");
	}
	
	public void handleContent(List<String> lines, ExcelExportHelper excelExportHelper) {
		int[] range = findRange(lines);
		int contentStart = range[0];
		int contentEnd = range[1];
		
		if (contentStart == -1) {
			return ;
		}

		String line = lines.get(contentStart);
		// 单条数据
		if (line.contains("=")) {
			handleSingleContent(lines, contentStart, contentEnd, excelExportHelper);
		} else {
			handleTableContent(lines, contentStart, contentEnd, excelExportHelper);
		}
	}
	
	protected void handleSingleContent(List<String> lines, int contentStart, int contentEnd, ExcelExportHelper excelExportHelper) {
		excelExportHelper.createRow();
		
		String address = lines.get(1).split(":")[1].trim(); 
		excelExportHelper.setCell(0, address);
		excelExportHelper.setCell(1, lines.get(2).split(":")[1]);
		
		int i = contentStart; 
		while (i < contentEnd) {
			String line = lines.get(i);
			
			List<String> contents = new ArrayList<String>();
			
			String[] array = null; 
			array = line.split("=");
			
			contents.add(array[0].trim());
			if (array[1].contains(":")) {
				array = array[1].split(":");
				
				contents.add(array[0].trim());
				contents.add(array[1].trim());
			} else {
				contents.add(array[1].trim());
			}
			
			if (!contents.get(0).equals("")) {
				Integer index = headMap.get(contents.get(0));
				if (index != null) {
					excelExportHelper.setCell(index, contents.get(1));
				} else {
					Cell cell = firstRow.createCell(firstRow.getLastCellNum());
					cell.setCellValue(contents.get(0));
					excelExportHelper.setCell(firstRow.getLastCellNum() - 1, contents.get(1));
					
					headMap.put(contents.get(0), new Integer(firstRow.getLastCellNum()) - 1);
				}
			} else {
				Integer index = headMap.get(contents.get(1));
				if (index != null) {
					excelExportHelper.setCell(index, contents.get(2));
				} else {
					Cell cell = firstRow.createCell(firstRow.getLastCellNum());
					cell.setCellValue(contents.get(1));
					excelExportHelper.setCell(firstRow.getLastCellNum() - 1, contents.get(2));
					
					headMap.put(contents.get(1), new Integer(firstRow.getLastCellNum()) - 1);
				}
			}
			
			i++;
		}
	}
	
	protected void handleTableContent(List<String> lines, int contentStart, int contentEnd, ExcelExportHelper excelExportHelper) {
		String headLine = lines.get(contentStart);
		String[] arrayHead = headLine.split("  +");

		int i = contentStart + 2;
		while (i < contentEnd) {
			String line = lines.get(i);
			String[] arrayValue = line.split("  +");

			excelExportHelper.createRow();

			String address = lines.get(1).split(":")[1].trim();
			excelExportHelper.setCell(0, address);
			excelExportHelper.setCell(1, lines.get(2).split(":")[1]);

			for (int j = 0; j < arrayHead.length; j++) {
				String h = arrayHead[j];
				Integer index = headMap.get(h);
				if (index != null) {
					excelExportHelper.setCell(index, arrayValue[j]);
				} else {

					if (firstRow.getLastCellNum() == 256) {
						break;
					}

					try {
						Cell cell = firstRow.createCell(firstRow
								.getLastCellNum());
						cell.setCellValue(arrayHead[j]);
						excelExportHelper.setCell(
								firstRow.getLastCellNum() - 1, arrayValue[j]);
						headMap.put(arrayHead[j],
								new Integer(firstRow.getLastCellNum()) - 1);
					} catch (Exception e) {
						break;
					}
				}
			}
			i++;
		}
	}
	
	public void handleHead(List<String> lines, ExcelExportHelper excelExportHelper) {
		int[] range = findRange(lines);
		int contentStart = range[0];
		int contentEnd = range[1];
		
		if (contentStart == -1) {
			return ;
		}
		
		String line = lines.get(contentStart);
		// 单条数据
		if (line.contains("=")) {
			handleSingleHead(lines, contentStart, contentEnd, excelExportHelper);
		} else {
			handleTableHead(lines, contentStart, contentEnd, excelExportHelper);
		}
		
		initHeadMap(excelExportHelper);
	}
	
	protected void handleSingleHead(List<String> lines, int contentStart, int contentEnd, ExcelExportHelper excelExportHelper) {
		excelExportHelper.createRow();

		excelExportHelper.setCellHeader(0, "网元");
		excelExportHelper.setCellHeader(1, "报文");
		
		int i = contentStart;
		while (i < contentEnd) {
			String line = lines.get(i);
			
			List<String> heads = new ArrayList<String>();
			
			String[] array = null; 
			array = line.split("=");
			
			heads.add(array[0].trim());
			if (array[1].contains(":")) {
				array = array[1].split(":");
				
				heads.add(array[0].trim());
				heads.add(array[1].trim());
			} else {
				heads.add(array[1].trim());
			}
			
			if (!heads.get(0).equals("")) {
				excelExportHelper.setCellHeader(i - contentStart + 2, heads.get(0));
			} else {
				excelExportHelper.setCellHeader(i - contentStart + 2, heads.get(1));
			}
			
			i++;
		}
	}
	
	protected void handleTableHead(List<String> lines, int contentStart, int contentEnd, ExcelExportHelper excelExportHelper) {
		excelExportHelper.createRow();

		excelExportHelper.setCellHeader(0, "网元");
		excelExportHelper.setCellHeader(1, "报文");

		int i = 2;
		String line = lines.get(contentStart);
		String[] array = line.split("  +");

		for (String head : array) {
			excelExportHelper.setCell(i, head);
			i++;
		}
	}
	
	private int[] findRange(List<String> lines) {
		int contentStart = -1;
		int contentEnd = -1;
		for (int i = 0; i < lines.size(); i++) {
			String line = lines.get(i);
			
			if (line.matches("--+")) {				
				contentStart = i + 1;  
			} else if (line.trim().startsWith("(结果个数") && contentStart > -1) {
				contentEnd = i;
				break;
			}
		}
		
		if (contentStart == -1) {
			for (int i = 0; i < lines.size(); i++) {
				String line = lines.get(i);
				
				if (line.equals("")) {				
					contentStart = i + 1;  
				} else if (line.trim().startsWith("(结果个数") && contentStart > -1) {
					contentEnd = i;
					break;
				}
			}
		}
		
		return new int[]{contentStart, contentEnd};
	}
	
	private void initHeadMap(ExcelExportHelper excelExportHelper) {
		// 因为命令输出的内容可能有不同，所以需要查找。
		// 得到第一行标题
		firstRow = excelExportHelper.getSheet().getRow(0);
		for (Cell cell : firstRow) {
			headMap.put(cell.getStringCellValue(), cell.getColumnIndex());
		}
	}
}
